package com.pbs.ui;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.pbs.contact.Contact;
import com.pbs.net.WSF;
import com.pbs.packdata.UserInfo;
import com.pbs.ui.dialog.Dialog;
import com.pbs.ui.dialog.Dialog.Type;
import com.pbs.utils.ContactProvider;
import com.pbs.utils.Date;
import com.pbs.utils.DateFormat;

public class SendContactActivity extends Activity {
	private ArrayList<UserInfo>		items		= new ArrayList<UserInfo>();
	private ListView				lv;
	private ArrayAdapter<UserInfo>	aa;
	private ContactProvider			cp;
	Handler							myHandler	= new Handler();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.send_contact);
		lv = (ListView) findViewById(R.id.List);
		try {
			cp = new ContactProvider();
			cp.setCr(getContentResolver());
			cp.setCur(getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, "display_name ASC"));
			items = WSF.getListUsername(AccountManagerScreen.getUserID());
			aa = new ArrayAdapter<UserInfo>(this, R.layout.item_username_info, items) {

				@Override
				public View getView(int position, View convertView, ViewGroup parent) {
					View v = convertView;
					if (v == null) {
						LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
						v = vi.inflate(R.layout.item_username_info, null);
					}

					UserInfo userinfo = items.get(position);
					if (userinfo != null) {
						TextView tvTopLeftInfo = (TextView) v.findViewById(R.id.tvTopLeftInfo);
						TextView tvBottomRightInfo = (TextView) v.findViewById(R.id.tvBottomRightInfo);
						CheckBox cb = (CheckBox) v.findViewById(R.id.chkSelectContact);
						cb.setChecked(userinfo.isChecked());
						tvTopLeftInfo.setText(userinfo.getDisplayname());
						tvBottomRightInfo.setText(userinfo.getUsername());
					}
					return v;
				}
			};
			lv.setAdapter(aa);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void radioButtonClick(View v) {
		int pos = lv.getPositionForView(v);
		items.get(pos).setChecked(((CheckBox) v).isChecked());
	}

	public void sendContactClick(View v) {
		if (items.isEmpty()) {
			Toast.makeText(this, "Don't have any friends in list",
					Toast.LENGTH_LONG);
			return;
		}
		boolean hasCheck = false;
		for (UserInfo info : items) {
			if (info.isChecked()) {
				hasCheck = true;
				break;
			}
		}
		if (hasCheck) {
			for (UserInfo a : items) {
				if (a.isChecked()) {
					final String receiver = a.getUsername();
					Log.i("Receiver", receiver);
					final EditText editTextNote = (EditText) findViewById(R.id.txtNote);
					final String notes = editTextNote.getText().toString();

					final String[] ids = getIntent().getExtras().getStringArray("ArrayId");
					final ProgressDialog pd = Dialog.showProgressDialog(this, "Read contact", "Please waiting...", false);
					new Thread(new Runnable() {
						@Override
						public void run() {
							try {
								ArrayList<Contact> contacts = new ArrayList<Contact>();
								for (String myid : ids) {
									Log.i("ID From Send Contact", " - value: " + myid);
									final Contact contact = cp.readContact(myid);
									contacts.add(contact);
									myHandler.post(new Runnable() {
										@Override
										public void run() {
											pd.setMessage(contact.getDisplayName());
										}
									});
								}
								myHandler.post(new Runnable() {
									@Override
									public void run() {
										pd.setTitle("Send contact");
										pd.setMessage("Please waiting...");
									}
								});
								final String msg = WSF.sentContactList(AccountManagerScreen.getUserID(), AccountManagerScreen.getUsername(), receiver, contacts, Date.getDate(DateFormat.DDMMYYYY, "-"), Date.getTime(),
									notes);

								myHandler.post(new Runnable() {
									@Override
									public void run() {
										getIntent().getExtras().clear();
										Toast.makeText(SendContactActivity.this, msg,
												Toast.LENGTH_LONG);
										pd.dismiss();
									}
								});

								InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
								imm.hideSoftInputFromWindow(editTextNote.getWindowToken(), 0);
								myHandler.post(new Runnable() {
									@Override
									public void run() {
										aa.notifyDataSetChanged();
										finish();
									}
								});

							} catch (final Exception e) {
								e.printStackTrace();
								myHandler.post(new Runnable() {
									@Override
									public void run() {
										pd.dismiss();
										Dialog.show(SendContactActivity.this, "Error!", e.getMessage(), null, null, null,
												null, Type.ERROR);
									}
								});
							}
						}
					}).start();

				}
			}

		} else {
			Toast.makeText(this, "Please choose any receivers",
					Toast.LENGTH_LONG);
		}
	}
}
